#ifndef __XKK_TCPCONNECTION_H__
#define __XKK_TCPCONNECTION_H__

#include "Noncopyable.hpp"
#include "Socket.hpp"
#include "SocketIO.hpp"
#include "InetAddress.hpp"

#include <memory>
#include <functional>

using namespace std;

namespace xkk
{

class EventLoop;

class TcpConnection;
using TcpConnectionPtr=shared_ptr<TcpConnection>;
using TcpConnectionCallback=function<void(const TcpConnectionPtr&)>;

class TcpConnection
    :Noncopyable
     ,public enable_shared_from_this<TcpConnection>
{
public:
    TcpConnection(int fd,EventLoop *); 
    ~TcpConnection();

    string receive();
    void send(const string &msg);
    void sendInLoop(const string &msg);

    string toString() const;
    void shutdown();

    void setConnectionCallback(const TcpConnectionCallback & cb)
    { _onConnection=cb;  }
    void setMessageCallback(const TcpConnectionCallback & cb)
    { _onMessage=cb;  }
    void setCloseCallback(const TcpConnectionCallback & cb)
    { _onClose=cb;  }

    void handleConnectionCallback();
    void handleMessageCallback();
    void handleCloseCallback();
private:
    InetAddress getLocalAddr();
    InetAddress getPeerAddr();
    
private:
    Socket _sock;
    SocketIO _socketIo;
    InetAddress _localAddr;
    InetAddress _peerAddr;
    bool _isShutdownWrite;

    EventLoop *_loop;

    TcpConnectionCallback _onConnection;
    TcpConnectionCallback _onMessage;
    TcpConnectionCallback _onClose;
};

}//end of namespace xkk
#endif
